package com.xuzz.study.io.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * buffer的分散于聚集
 */
public class ScattingAndGathering {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        SocketChannel accept = serverSocketChannel.accept();
        int msgLength = 8 ;
        while(true)
        {
            int byteRead = 0;
            while(byteRead< msgLength)
            {
                long l = accept.read(byteBuffers);
                byteRead+=l;
                //byteRead = byteRead+ l ,这样写会报错

                Arrays.asList(byteBuffers).stream().map(buffer->
                        "position:"+buffer.position()+",limit:"+buffer.limit())
                .forEach(System.out::println);
            }

            Arrays.asList(byteBuffers).forEach(buffer->
                buffer.flip());

            long byteWrite = 0 ;
            while(byteWrite<msgLength)
            {
               long l =  accept.write(byteBuffers);
               byteWrite+=l;
            }
            Arrays.asList(byteBuffers).forEach(buffer->

                        buffer.clear()
                    );

            System.out.println("byteRead:="+byteRead+" byteWrite:="+byteWrite+" msgLength:="+msgLength);
        }
    }
}
